package com.klikmee.sms.chat.web.dao;

import java.util.Date;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TemporalType;

import com.klikmee.sms.services.chat.model.Subscriber;

public class SubscriberDAO extends AbstractDAO<Subscriber> {

	public SubscriberDAO() {
		super(Subscriber.class);

	}

	/**
	 * Checks if user has a record in Subscriber's table and updates subscription date to current if true.
	 * 
	 * @param phonenumber
	 *            MSISDN of the subscriber
	 * @return true if does have active session, otherwise false
	 */
	public boolean checkIfHasActiveSessionAndUpdate(String phonenumber) {
		try {
			// find by phonenumber and active state
			Subscriber result = (Subscriber) entityManager.createNamedQuery("Subscriber.findByPhonenumberAndState").setParameter("phonenumber", phonenumber).setParameter("unsubscribed", false)
					.getSingleResult();

			if (result != null) {
				result.setSubscriptionDate(new Date());
				edit(result);
				return true;
			}
		} catch (NoResultException e) {

		}
		return false;
	}

	/**
	 * Updates {@link Subscriber} by setting {@link Subscriber#setUnsubscribed(boolean)} to true where subscription date is before param lastMonth.
	 * 
	 * @param lastMonth
	 *            date representing limit for active subscriptions.
	 * @return number of updated (disabled) subscriptions
	 */
	public int disableExpiredSubscriptions(Date lastMonth) {
		Query query = entityManager.createNamedQuery("Subscriber.updateExpired");
		query.setParameter("lastMonth", lastMonth, TemporalType.TIMESTAMP);
		int updatedRows = query.executeUpdate();

		return updatedRows;
	}

	/**
	 * Disables subscription identified by MSISDN
	 * @param phonenumber
	 */
	public int disableSubscription(String phonenumber){
		return entityManager.createNamedQuery("Subscriber.unsubscribeByPhonenumber").setParameter("phonenumber", phonenumber).executeUpdate();
	}
	
	/**
	 * Finds subscriber by it's phone number.
	 * 
	 * @param phonenumber
	 *            phone number of the subscriber
	 * @return instance of {@link Subscriber} if found, null otherwise.
	 */
	public Subscriber findByPhonenumber(String phonenumber) {

		try {
			Subscriber subsciber = (Subscriber) entityManager.createNamedQuery("Subscriber.findByPhonenumber").setParameter("phonenumber", phonenumber).getSingleResult();
			return subsciber;
		} catch (NoResultException e) {
			return null;
		}
	}
}
